package com.fl.nj.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于测试CORS配置的控制器
 * 这个控制器会明确地设置CORS头信息，帮助我们诊断跨域问题
 */
@RestController
@RequestMapping("/api/test-cors")
public class TestCorsController {

    /**
     * 测试端点1：不使用注解，手动设置CORS头信息
     */
    @GetMapping("/manual")
    public Map<String, String> testManualCors(HttpServletResponse response) {
        // 手动设置CORS头信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        
        // 返回测试数据
        Map<String, String> result = new HashMap<>();
        result.put("message", "This is a manual CORS test");
        result.put("status", "success");
        return result;
    }
    
    /**
     * 测试端点2：使用@CrossOrigin注解设置CORS
     */
    @GetMapping("/annotation")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {org.springframework.web.bind.annotation.RequestMethod.GET, org.springframework.web.bind.annotation.RequestMethod.POST, org.springframework.web.bind.annotation.RequestMethod.PUT, org.springframework.web.bind.annotation.RequestMethod.DELETE, org.springframework.web.bind.annotation.RequestMethod.OPTIONS})
    public Map<String, String> testAnnotationCors() {
        // 返回测试数据
        Map<String, String> result = new HashMap<>();
        result.put("message", "This is an annotation CORS test");
        result.put("status", "success");
        return result;
    }
}